﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VehicleMaintenance.Framework;
using VehicleMaintenance.Models;
using MySql.Data.MySqlClient;

namespace VehicleMaintenance
{
	public partial class LoginForm : BaseForm
	{
		public LoginForm()
		{
			InitializeComponent();
		}

		private void btnLogin_Click(object sender, EventArgs e)
		{
			//this.ShowInfo(VehicleMaintenance.Comm.SystemInfo.GetMoc()[0] + "," + VehicleMaintenance.Comm.SystemInfo.GetMoc()[1] + "," +VehicleMaintenance.Comm.SystemInfo.GetMoc()[2] + "," );
			//return;
			try
			{
				this.errorProvider1.Clear();
				if (txtUserName.Text.Trim().Length == 0)
				{
					this.errorProvider1.SetError(txtUserName, "请输入用户名！");
					txtUserName.Focus();
					return;
				}
				if (txtPwd.Text.Trim().Length == 0)
				{
					this.errorProvider1.SetError(txtPwd, "请输入用户口令！");
					txtPwd.Focus();
					return;
				}
				CarDBContext db = new CarDBContext();
				User user = db.Users.FirstOrDefault(p => p.UserCode == txtUserName.Text.Trim() && p.PassWord == txtPwd.Text);
				if (user == null)
				{
					this.ShowInfo("用户名或口令错误！");
					txtPwd.Clear();
					txtPwd.Focus();
					return;
				}
				else
				{
					MainForm2 form = new MainForm2();
					MainForm2.User = user;
					form.Show();
					//this.ShowInTaskbar = false;
					this.Hide();
				}
			}
			catch (ProviderIncompatibleException ex)
			{
				MySql.Data.MySqlClient.MySqlException myEx = ex.InnerException as MySql.Data.MySqlClient.MySqlException;
				if (myEx != null)
				{
					switch (myEx.Number)
					{
						case 1049://数据库不存在
							string err = VehicleMaintenance.Comm.DataBaseComm.CreatDataBase();
							if(err.Length > 0)
							{
								this.ShowInfo(err);								
							}
							break;
						case 1146://数据库表不存在
							{
								VehicleMaintenance.Comm.DataBaseComm.Restore(System.IO.Path.Combine(Application.StartupPath, "Car_Empty.bak"));
								this.ShowInfo("数据表创建成功，请重新登录");
							}
							break;
						default:
							MessageBox.Show(ex.Message);
							break;
					}
				}
			}
			catch (Exception ex)
			{
				this.ShowInfo(ex.Message);
			}
		}

		private void btnClose_Click(object sender, EventArgs e)
		{
			try
			{
				this.Close();
			}
			catch (Exception ex)
			{
				this.ShowInfo(ex.Message);
			}
		}
	}
}
